package gps.monitor.jt809server.protocol.codec;

import gps.monitor.jt809server.entity.DownPlatformAccount;
import gps.monitor.jt809server.protocol.model.AbstractJt809Message;
import gps.monitor.jt809server.protocol.Jt809ParseException;
import gps.monitor.jt809server.protocol.model.Jt809MessageHeader;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

/**
 * @author cyq
 * @date 2021/11/7
 * @desc talk is cheep,show me the code
 */
public interface IJt809Handler {

    /**
     * 流数据将被消耗掉 readed
     * @param byteBuf 完整包体
     * @throws Jt809ParseException
     * @return Jt809Message 完整的消息体
     */
    AbstractJt809Message read(ByteBuf byteBuf, DownPlatformAccount account) throws Jt809ParseException;

    /**
     * 解析header
     * 流数据将被消耗掉
     * @param byteBuf 传入的数据应该是完整的包
     */
    default Jt809MessageHeader readGeneralHeader(ByteBuf byteBuf) throws Jt809ParseException {

        byteBuf.readByte();//5B
        Jt809MessageHeader header = new Jt809MessageHeader();
        header.setMsgLength(Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(4)),16));
        header.setMsgSn(Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(4)),16));
        header.setMsgId(Integer.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(2)),16));
        header.setMsgGnssCenterId(Long.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(4)),16));
        header.setVersionFlag(ByteBufUtil.hexDump(byteBuf.readBytes(3)));
        header.setEncryptFlag(byteBuf.readByte());
        header.setEncryptKey(Long.valueOf(ByteBufUtil.hexDump(byteBuf.readBytes(4)),16));

        return header;
    }
}
